package cn.edu.gduf.luowowo.website.web.controller;

import cn.edu.gduf.luowowo.article.domain.Destination;
import cn.edu.gduf.luowowo.article.domain.StrategyDetail;
import cn.edu.gduf.luowowo.article.query.StrategyDetailQuery;
import cn.edu.gduf.luowowo.article.service.IDestinationService;
import cn.edu.gduf.luowowo.article.service.IStrategyCommendService;
import cn.edu.gduf.luowowo.article.service.IStrategyDetailService;
import cn.edu.gduf.luowowo.article.service.IStrategyTagService;
import cn.edu.gduf.luowowo.cache.domain.StrategyStatisVO;
import cn.edu.gduf.luowowo.cache.service.IStrategyStatisVoRedisService;
import cn.edu.gduf.luowowo.comment.domain.StrategyComment;
import cn.edu.gduf.luowowo.comment.query.StrategyCommentQuery;
import cn.edu.gduf.luowowo.comment.service.IStrategyCommentService;
import cn.edu.gduf.luowowo.common.exception.LogicException;
import cn.edu.gduf.luowowo.common.util.AjaxResult;
import cn.edu.gduf.luowowo.member.domain.UserInfo;
import cn.edu.gduf.luowowo.search.query.StrategySearchQuery;
import cn.edu.gduf.luowowo.search.service.IStrategySearchService;
import cn.edu.gduf.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/strategy")
public class StrategyController {
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyTagService strategyTagService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private IStrategyStatisVoRedisService strategyStatisVoRedisService;
    @Reference
    private IStrategyCommendService strategyCommendService;
    @Reference
    private IStrategySearchService strategySearchService;

    @RequestMapping("")
    public String index(Model model) {
        //commends 攻略推荐，首页的轮播图
        model.addAttribute("commends", strategyCommendService.queryTop5());
        //hotCds 热门攻略推荐排行(数据在redis中，拿到startegy_statis_zset_hot,得到vo的key集合,再将vokey转为vo对象)
        model.addAttribute("hotCds", strategyStatisVoRedisService.listStrategyStatisHotTop10());
        //查询所有的攻略，再筛选出国内的10个和国外的10个
        List<StrategyStatisVO> list = strategyStatisVoRedisService.queryStrategyStatisVOs();
        List<StrategyStatisVO> abroadCds = new ArrayList<>();
        List<StrategyStatisVO> unabroadCds = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (StrategyStatisVO vo : list) {
                if (vo.isIsabroad()) {
                    //abroadCds 海外攻略推荐排行(国外)
                    if (abroadCds.size() < 10) {
                        abroadCds.add(vo);
                    }
                } else {
                    //unabroadCds 国内攻略推荐排行
                    if (unabroadCds.size() < 10) {
                        unabroadCds.add(vo);
                    }
                }
            }
        }
        model.addAttribute("unabroadCds", unabroadCds);
        model.addAttribute("abroadCds", abroadCds);

        //themeCds 主题推荐; 1:只要前10个；2:去除目的地重复的;3:按照该主题所关联的攻略文章数量排序
        List<Map<String, Object>> map = strategySearchService.queryThemeTop10();
        model.addAttribute("themeCds", map);
        //themes主题
        model.addAttribute("themes",strategySearchService.queryConditionTheme());
        //provinces国内
        model.addAttribute("provinces", strategySearchService.queryConditionProvince());
        //abroads国外
        model.addAttribute("abroads", strategySearchService.queryConditionAbroad());
        return "strategy/index";
    }

    @RequestMapping("/searchPage")
    public String searchPage(Model model, @ModelAttribute("qo")StrategySearchQuery qo){
        model.addAttribute("page", strategySearchService.queryCondition(qo));
        return "strategy/searchPageTpl";
    }

    @RequestMapping("/detail")
    public String detail(Model model, Long id,@UserParam UserInfo userInfo) {
        //查询出detail以及它的内容
        StrategyDetail detail = strategyDetailService.get(id);
        detail.setStrategyContent(strategyDetailService.getContent(id));
        model.addAttribute("detail", detail);
        //阅读数 + 1
        strategyStatisVoRedisService.viewnumIncrease(id, 1);
        model.addAttribute("vo", strategyStatisVoRedisService.getVO(id));
        model.addAttribute("uids", strategyStatisVoRedisService.getUids(id));

        model.addAttribute("sids", strategyStatisVoRedisService.getSids(userInfo.getId()));

        //热门攻略推荐分数 + 1
        strategyStatisVoRedisService.addHotScore(id, 1);
        return "strategy/detail";
    }

    @RequestMapping("/list")
    public Object list(Model model, @ModelAttribute("qo") StrategyDetailQuery qo) {
        //toast
        //dest
        List<Destination> toasts = destinationService.getToasts(qo.getDestId());
        Destination dest = new Destination();
        if (toasts.size() > 0) {
            dest = toasts.remove(toasts.size() - 1);
        }
        model.addAttribute("toasts", toasts);
        model.addAttribute("dest", dest);
        //tags
        model.addAttribute("tags", strategyTagService.list());
        //pageInfo
        model.addAttribute("pageInfo", strategyDetailService.query1(qo));
        return "strategy/list";
    }

    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentAdd(Model model, StrategyComment comment, @UserParam UserInfo user) {
        if (user == null) {
            throw new LogicException("请先登录");
        }
        comment.setCity(user.getCity());
        comment.setUserId(user.getId());
        comment.setUsername(user.getNickname());
        comment.setLevel(user.getLevel());
        comment.setHeadUrl(user.getHeadImgUrl());
        strategyCommentService.saveOrUpdate(comment);
        //评论数 + 1
        strategyStatisVoRedisService.replynumIncrease(comment.getDetailId(), 1);
        StrategyStatisVO vo = strategyStatisVoRedisService.getVO(comment.getDetailId());
        //热门攻略推荐分数 + 1  第一个参数是攻略id
        strategyStatisVoRedisService.addHotScore(comment.getDetailId(), 1);
        return AjaxResult.SUCCESS.addData(vo.getReplynum());
    }

    @RequestMapping("/comment")
    public String comment(Model model, @ModelAttribute("qo") StrategyCommentQuery qo) {
        model.addAttribute("page", strategyCommentService.query(qo));
        return "strategy/commentTpl";
    }

    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(String toid, Long fromid) {
        strategyCommentService.thumbUp(toid, fromid);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long sid, @UserParam UserInfo userInfo) { //sid 表示攻略id
        //用户未登录
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "登录后操作");
            result.setCode(102);
            return result;
        }
        //调用方法，与 点赞/取消点赞类似
        boolean ret = strategyStatisVoRedisService.favor(sid, userInfo.getId());
        //攻略推荐分数 +1 或者-1
        strategyStatisVoRedisService.addCommendScore(sid, ret ? 1 : -1);
        return new AjaxResult(ret).addData(strategyStatisVoRedisService.getVO(sid));
    }

    @RequestMapping("/strategyThumbup")
    @ResponseBody
    public Object thumbup(Long sid, @UserParam UserInfo userInfo) { //sid 表示攻略id
        //用户未登录
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "登录后操作");
            result.setCode(102);
            return result;
        }
        boolean ret = strategyStatisVoRedisService.thumbSup(sid, userInfo.getId());
        if (ret) {
            //攻略推荐分数 +1
            strategyStatisVoRedisService.addCommendScore(sid, 1);
        }
        return new AjaxResult(ret).addData(strategyStatisVoRedisService.getVO(sid));
    }


    //分享
    @RequestMapping("share")
    @ResponseBody
    public Object sina(Long detailId){

        try {
            strategyStatisVoRedisService.updateSharenum(detailId);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"分享失败");
        }
        return AjaxResult.SUCCESS;
    }

}
